package org.example.app.order.executor;

import com.alibaba.cola.dto.Response;
import org.example.app.order.assembler.OrderAssembler;
import org.example.app.order.validator.OrderValidator;
import org.example.client.order.dto.cmd.OrderCreateCmd;
import org.example.domain.order.domainservice.OrderCreateDomainService;
import org.example.domain.order.entity.OrderEntity;
import org.example.domain.order.gateway.OrderGateway;
import org.example.domain.order.gateway.OrderItemGateway;
import org.example.infrastructure.common.util.ProducerUtil;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;

@Component
public class OrderCreateCmdExe {

    @Resource
    private OrderValidator validator;
    @Resource
    private OrderCreateDomainService orderCreateDomainService;
    @Resource
    private OrderGateway orderGateway;
    @Resource
    private OrderItemGateway orderItemGateway;
    @Resource
    private OrderAssembler assembler;
    @Resource
    private ProducerUtil producerUtil;

    public Response execute(OrderCreateCmd orderCreateCmd) {
        // 校验
        validator.validateOrderCreateCmd(orderCreateCmd);
        // 转换
        OrderEntity orderEntity = assembler.toEntity(orderCreateCmd);
        // 调用领域服务执行业务逻辑
        orderCreateDomainService.process(orderEntity);
        // 保存订单
        Long orderId = orderGateway.insert(orderEntity);
        // 将订单 id 组装到订单商品中
        orderEntity.setOrderItemListOrderId(orderId);
        // 保存订单商品列表
        orderItemGateway.insertBatch(orderEntity.getOrderItemList());
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                // 模拟发送延时消息，超时未支付取消订单
                producerUtil.sendDelay();
            }
        });
        return Response.buildSuccess();
    }
}
